package 二叉树系列;

import java.util.*;

public class IterateTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.empty()){
            TreeNode treeNode = stack.peek();
            stack.pop();
            result.add(treeNode.val);
            if(treeNode.right!=null){
                stack.push(treeNode.right);
            }
            if(treeNode.left!=null){
                stack.push(treeNode.left);
            }
        }
        return result;
    }
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root==null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null && !stack.empty()){
            if(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }else{
                cur = stack.pop();
                result.add(cur.val);
                cur = cur.right;
            }
        }
        return result;
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root==null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode treeNode = stack.pop();
            result.add(treeNode.val);
            if(treeNode.left!=null){
                stack.push(treeNode.left);
            }
            if(treeNode.right!=null){
                stack.push(treeNode.right);
            }

        }
        Collections.reverse(result);
        return result;
    }
}
